import { useEffect } from 'react';
import { connect } from 'react-redux';
import { Navigate } from 'react-router-dom';
import { showPermissions } from '@/apis/user/index';
import { SAVE_PERMISSIONS } from '@/reducers/common';
import { dispatchWithPromise } from '@/utils/util';
import config from '../../../config.default'

function PrivateComponent(props: any) {
    const getPermissions = async () => {
        let res = await showPermissions({})
        if (res.data.length == 0) {
            res.data = [{}]
        }
        await dispatchWithPromise({ type: SAVE_PERMISSIONS, data: res.data })
    }
    useEffect(() => {
        const { loginInfo, permissions } = props;
        if (!loginInfo) {
            return;
        }
        if ((!permissions || !permissions.length)) {
            getPermissions()
        }
        return
    }, [props])
    return (
        typeof props.loginInfo !== 'boolean' ? props.children : (config.loginPermissions.enable ? <Navigate to="/login" /> : props.children)
    )

}

export default connect((state: any) => {
    let { loginInfo, permissions, tenantInfo } = state.common;
    let l = localStorage['persist:__info__'] || null
    if (!l) {
        return {
            loginInfo: false,
            permissions: []
        }
    }
    l = JSON.parse(l).loginInfo
    l = JSON.parse(l)
    if (l && l.accountName && loginInfo && loginInfo.accountName && loginInfo.accountName != l.accountName) {
        permissions = []
    }
    return {
        loginInfo,
        permissions,
        tenantInfo
    }
})(PrivateComponent)